package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper logsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        //1 添加任务到数据库
        Boolean flag = addTaskToDB(task);

        //2. 添加数据到redis
        if(flag){
            addTaskToRedis(task);
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        //1. 删除和更新数据库中的数据
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        //2.如果成功则删除redis的数据
        Boolean flag = Boolean.TRUE;

        if(null != task){
            flag = removeTaskFromCache(task);
        }
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        //1. 构建redis的key
        String key = ScheduleConstants.TOPIC + type + "_" + priority;

        //2. 通过key到redis中获取任务数据
        String json_task = cacheService.lRightPop(key);

        //3. 如果任务数据不为空则转换位Task对象
        if(StringUtils.isNotEmpty(json_task)){
            Task task = JSON.parseObject(json_task, Task.class);

            //更新任务的状态位1
            updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            return task;
        }

        //4. 返回结果
        return null;
    }

    /**
     * 删除redis中的任务数据
     * @param task
     * @return
     */
    private Boolean removeTaskFromCache(Task task) {
        //1. 获取当前时间和未来5分钟的时间
        long currentTimeMillis = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance(); // 日历类
        calendar.add(Calendar.MINUTE, 5);
        long nextTime = calendar.getTimeInMillis();
        //2. 判断任务执行的时间
        long count = -1;
        if(task.getExecuteTime() <= currentTimeMillis){
            String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
            //3. 删除数据
            count = cacheService.lRemove(key, 0, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= nextTime){
            String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
            //3. 删除数据
            count = cacheService.zRemove(key, JSON.toJSONString(task));
        }

        return count == 1 ? true:false;
    }

    /**
     * 删除任务数据 更新任务的日志的状态数据
     * @param taskId
     * @return
     */
    private Task updateDb(long taskId, int status) {
        try {
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs logs = logsMapper.selectById(taskId);
            logs.setStatus(status);
            logsMapper.updateById(logs);

            Task task = new Task();
            BeanUtils.copyProperties(logs, task);
            task.setExecuteTime(logs.getExecuteTime().getTime());

            return task;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存任务到redis
     * @param task
     */
    private void addTaskToRedis(Task task) {
        //1. 获取当前时间和未来5分钟的时间
        long currentTimeMillis = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance(); // 日历类
        calendar.add(Calendar.MINUTE, 5);
        long nextTime = calendar.getTimeInMillis();

        //2. 比较任务执行的时间 如果是《=当前时间则添加到list集合  如果《= 未来5分钟的时间则添加到zset
        if(task.getExecuteTime() <= currentTimeMillis){
            String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= nextTime){
            String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
            cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 保存任务数据到数据库
     * @param task
     * @return
     */
    private Boolean addTaskToDB(Task task) {
        Boolean flag = Boolean.TRUE;

        try {
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

            taskinfoMapper.insert(taskinfo);

            TaskinfoLogs logs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, logs);
            logs.setVersion(1);
            logs.setStatus(ScheduleConstants.SCHEDULED);
            logsMapper.insert(logs);

            task.setTaskId(taskinfo.getTaskId());
        } catch (BeansException e) {
            e.printStackTrace();
            flag = Boolean.FALSE;
        }

        return flag;
    }


    /**
     * 刷新未来数据到list集合
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if(StringUtils.isNotEmpty(token)){
            log.info("未来数据定时刷新---定时任务");

            //1 得到未来数据的所有的key
            Set<String> keys = cacheService.scan(ScheduleConstants.FUTURE + "*");//[future_1_50,future_1_49]
            //2. 判断keys是否为空
            if(null != keys && keys.size() > 0){
                //3. 如不为空则遍历所有的可以
                for (String key : keys) {
                    Set<String> tasks = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());

                    //构建添加到的list集合的key
                    String[] futureKey = key.split("future_");
                    String topicKey = ScheduleConstants.TOPIC + futureKey[1];//topic_1_50

                    if(!tasks.isEmpty()){
                        cacheService.refreshWithPipeline(key, topicKey, tasks);
                        log.info("成功的将"+futureKey+"刷新到了"+topicKey);
                    }
                }
            }

            cacheService.relaseLock("FUTURE_TASK_SYNC");
        }
    }

    /**
     * 每5分钟查询一次数据库里面的数据-未来5分分钟之内要执行的任务 然后添加到redis中(添加之前需要删除redis中的老数据否则会出现数据重复的情况)
     * PostConstruct 注解作用：
     *  当当前的对象被创建以后就会立刻调用用来完成一些参数的初始化操作-xml的代码 init方法
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        log.info("查询数据库中的未来5分钟要执行的任务---定时任务");

        //1. 清空redis的缓存
        clearCache();

        //2. 查询未来5分钟要执行的任务
        Calendar calendar = Calendar.getInstance(); // 日历类
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        //3. 判断是否有任务 如果有则一个一个的添加到redis
        if(!taskinfoList.isEmpty()){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());

                addTaskToRedis(task);
            }
            log.info("加载数据库中的数据: " + taskinfoList + "到redis中");
        }
    }

    //清空redis的缓存
    private void clearCache() {
        Set<String> future_keys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topic_keys = cacheService.scan(ScheduleConstants.TOPIC + "*");

        cacheService.delete(future_keys);
        cacheService.delete(topic_keys);
    }
}
